<template>
  <view class="feedback-detail-container">
    <!-- 主要内容区 -->
    <view class="content">
      <!-- 学生信息 -->
      <view class="student-info">
        <text class="info-label">学生姓名：</text>
        <text class="info-value">{{ feedbackInfo.studentName || '未知学生' }}</text>
      </view>
      <view class="student-info">
        <text class="info-label">课程名称：</text>
        <text class="info-value">{{ feedbackInfo.courseName || '未知课程' }}</text>
      </view>
      <view class="student-info">
        <text class="info-label">班级名称：</text>
        <text class="info-value">{{ feedbackInfo.className || '未知班级' }}</text>
      </view>

      <!-- 学生表现评分 -->
      <view class="form-section">
        <text class="section-title">学生表现</text>
        <uni-rate 
          v-model="form.score" 
          :disabled="false" 
          :size="24"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          @change="setScore"
        />
        <text class="score-text">{{ form.score }}分</text>
      </view>

      <!-- 教学成果 -->
      <view class="form-section">
        <text class="section-title">教学成果</text>
        
        <!-- 文件上传切换 -->
        <view class="upload-toggle">
          <button 
            :class="['toggle-btn', !uploadVideo ? 'active' : '']" 
            @click="uploadVideo = false"
          >
            图片上传
          </button>
          <button 
            :class="['toggle-btn', uploadVideo ? 'active' : '']" 
            @click="uploadVideo = true"
          >
            视频上传
          </button>
        </view>

        <!-- 图片上传 -->
        <view class="upload-area" v-if="!uploadVideo">
          <view class="upload-list" v-if="fileList.length > 0">
            <view 
              class="upload-item" 
              v-for="(file, index) in fileList" 
              :key="index"
            >
              <image 
                :src="file.url" 
                mode="aspectFill" 
                class="upload-image"
                @click="previewImage(index)"
                :data-index="index"
              ></image>
              <view class="delete-btn" @click="deleteFile(index)">×</view>
            </view>
          </view>
          <view class="upload-btn" @click="chooseImage">
            <text class="upload-icon">+</text>
            <text class="upload-text">添加图片</text>
          </view>
        </view>

        <!-- 视频上传 -->
        <view class="upload-area" v-else>
          <view class="video-upload" @click="chooseVideo">
            <text class="upload-icon">📹</text>
            <text class="upload-text">点击上传视频</text>
          </view>
          <view class="video-preview" v-if="videoUrl">
            <video 
              :src="videoUrl" 
              controls 
              class="video-player"
              :autoplay="false"
            ></video>
            <view class="delete-btn" @click="deleteVideo">×</view>
          </view>
        </view>
      </view>

      <!-- 教师反馈 -->
      <view class="form-section">
        <text class="section-title">教师反馈</text>
        <textarea 
          v-model="form.comment" 
          class="feedback-textarea"
          placeholder="请输入教师反馈内容"
          :disabled="false"
        ></textarea>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitFeedback">
        提交反馈
      </button>
    </view>
  </view>
</template>

<script>
  import request from '@/utils/request'

  export default {
    data() {
      return {
        // 反馈信息
        feedbackInfo: {
          id: '',
          studentId: '',
          studentName: '',
          courseName: '',
          className: '',
          courseId: '',
          classId: ''
        },
        // 表单数据
        form: {
          id: '',
          studentId: '',
          studentName: '',
          score: 0,
          comment: '',
          filePaths: []
        },
        // 文件列表
        fileList: [],
        // 视频URL
        videoUrl: '',
        // 是否上传视频
        uploadVideo: false
      }
    },
    onLoad(options) {
      // 获取传递的参数
      if (options) {
        this.feedbackInfo = {
          id: options.id || '',
          studentId: options.studentId || '',
          studentName: options.studentName || '',
          courseName: options.courseName || '',
          className: options.className || '',
          courseId: options.courseId || '',
          classId: options.classId || ''
        }
        
        // 初始化表单数据
        this.form.id = this.feedbackInfo.id
        this.form.studentId = this.feedbackInfo.studentId
        this.form.studentName = this.feedbackInfo.studentName
        
        // 如果有ID，加载已有数据
        if (this.feedbackInfo.id) {
          this.loadFeedbackData()
        }
      }
    },
    methods: {
      // 返回上一页
      handleBack() {
        uni.navigateBack()
      },
      
      // 加载反馈数据
      loadFeedbackData() {
        request({
          url: `/ysg/work/getSignInRecord?id=${this.feedbackInfo.id}`,
          method: 'GET'
        }).then(res => {
          if (res.code === 200 && res.data) {
            const data = res.data
            this.form.score = Number(data.score) || 0
            this.form.comment = data.comment || ''
            
            // 处理文件路径
            if (data.filePaths) {
              try {
                const filePaths = JSON.parse(data.filePaths)
                // 分类图片和视频
                this.fileList = []
                this.videoUrl = ''
                
                filePaths.forEach(path => {
                  // 获取文件后缀
                  const ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase()
                  // 判断文件类型
                  if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext)) {
                    // 图片类型
                    this.fileList.push({ url: path })
                  } else if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) {
                    // 视频类型（只保留第一个视频）
                    if (!this.videoUrl) {
                      this.videoUrl = path
                    }
                  }
                })
              } catch (e) {
                console.warn('解析文件路径失败', e)
              }
            }
          }
        }).catch(error => {
          console.warn('获取反馈详情失败', error)
        })
      },
      
      // 设置评分
      setScore(e) {
        // uni-rate组件的change事件返回的是包含value属性的对象
        this.form.score = Number(e.value || e) || 0
      },
      
      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 9 - this.fileList.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const tempFilePaths = res.tempFilePaths
            tempFilePaths.forEach(path => {
              this.fileList.push({ url: path })
            })
          }
        })
      },
      
      // 删除文件
      deleteFile(index) {
        this.fileList.splice(index, 1)
      },
      
      // 预览图片
      previewImage(index) {
        const urls = this.fileList.map(file => file.url)
        uni.previewImage({
          current: index,
          urls: urls,
          fail: (err) => {
            console.error('预览图片失败', err)
          }
        })
      },
      
      // 选择视频
      chooseVideo() {
        uni.chooseVideo({
          sourceType: ['album', 'camera'],
          maxDuration: 60,
          camera: 'back',
          success: (res) => {
            this.videoUrl = res.tempFilePath
          }
        })
      },
      
      // 删除视频
      deleteVideo() {
        this.videoUrl = ''
      },
      
      // 提交反馈
      submitFeedback() {
        if (this.form.score === 0) {
          uni.showToast({
            title: '请选择学生表现评分',
            icon: 'none'
          })
          return
        }
        
        // 合并图片和视频路径
        const allFilePaths = [...this.fileList.map(file => file.url)]
        if (this.videoUrl) {
          allFilePaths.push(this.videoUrl)
        }
        
        // 准备提交数据
        const submitData = {
          ...this.form,
          filePaths: JSON.stringify(allFilePaths)
        }
        
        request({
          url: '/ysg/work/rate',
          data: submitData,
          method: 'POST'
        }).then(res => {
          if (res.code === 200) {
            uni.showToast({
              title: '提交成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            uni.showToast({
              title: '提交失败：' + (res.msg || '未知错误'),
              icon: 'none'
            })
          }
        }).catch(error => {
          console.error('提交反馈失败:', error)
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .feedback-detail-container {
    background-color: #f5f5f5;
    min-height: 100vh;
  }

  /* 页面标题 */
  .page-header {
    background-color: #ffffff;
    padding: 15px;
    border-bottom: 1px solid #e9ecef;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .back-icon {
    font-size: 20px;
    color: #333;
  }

  .header-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  /* 内容区 */
  .content {
    padding: 15px;
    background-color: #ffffff;
    margin: 10px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  /* 学生信息 */
  .student-info {
    display: flex;
    margin-bottom: 15px;
    align-items: center;
  }

  .info-label {
    font-size: 14px;
    color: #666;
    width: 80px;
  }

  .info-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  /* 表单区块 */
  .form-section {
    margin-bottom: 20px;
  }

  .section-title {
    display: block;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }

  /* 评分 */
  .score-text {
    display: block;
    font-size: 14px;
    color: #666;
    margin-top: 5px;
  }

  /* 文件上传切换 */
  .upload-toggle {
    display: flex;
    margin-bottom: 15px;
    gap: 10px;
  }

  .toggle-btn {
    flex: 1;
    height: 36px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    font-size: 14px;
    background-color: #f5f7fa;
    color: #606266;
  }

  .toggle-btn.active {
    background-color: #409eff;
    color: white;
    border-color: #409eff;
  }

  /* 图片上传 */
  .upload-area {
    margin-bottom: 15px;
  }

  .upload-list {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 10px;
  }

  .upload-item {
    position: relative;
    width: 80px;
    height: 80px;
  }

  .upload-image {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
  }

  .delete-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 20px;
    height: 20px;
    background-color: #ff4d4f;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    line-height: 1;
  }

  .upload-btn {
    width: 80px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 5px;
    background-color: #fafafa;
  }

  .upload-icon {
    font-size: 24px;
    color: #909399;
  }

  .upload-text {
    font-size: 12px;
    color: #909399;
  }

  /* 视频上传 */
  .video-upload {
    width: 100%;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    background-color: #fafafa;
  }

  /* 视频预览 */
  .video-preview {
    position: relative;
    margin-top: 10px;
    width: 100%;
  }

  .video-player {
    width: 100%;
    height: 200px;
    border-radius: 8px;
  }

  /* 反馈文本框 */
  .feedback-textarea {
    width: 100%;
    min-height: 120px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 10px;
    font-size: 14px;
    line-height: 1.5;
    resize: vertical;
  }

  /* 提交按钮 */
  .submit-btn {
    width: 100%;
    height: 45px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: bold;
    margin-top: 20px;
  }
</style>